$(function(){
    asyncData.choose_image();/*选择图片*/
    button.back();/*返回按钮*/
    button.mail_list();/*返回首页按钮*/
    time.choose_born();/*出生日期*/
    form.checkform();/*验证表单*/
    add.addteam();/*添加组*/
    add.newteam();
    
    render.initList();
    bindEvent.saveteam();
    bindEvent.save_people();
   
});
function GetQueryString(name)
{
     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null)return  unescape(r[2]); return null;
};/*获取地址栏URL*/
var asyncData={
	choose_image:function(){
        $("#choose_people").on("click",function(){
            $("#choose_image").click();
            $("#choose_image").change(function(){
            var file=$("#choose_image");
            var fils=file.get(0).files[0];
            var fordate=new FormData();
            fordate.append('pic',fils);
             var srcc=window.URL.createObjectURL(fils); 
             $("#choose_people").attr("src",srcc);
                 $.ajax({  
                  url:'http://localhost:8080/contacts/contact/imgUpload',  
                  type: 'POST',  
                  data: fordate,
                  async: false,  
                  cache: false,  
                  contentType: false,  
                  processData: false,  
                  success: function (data) {  
                    var json=eval('('+data+')');
                  
                    if(json.result==0){
                            alert("成功上传");
                          
                    }else if(json.result==1){
                        alert("导入失败");
                    }
                  },  
                  error: function (data) { 
                    alert("导入失败");
                  }  
         });  
            })
            
        })
    }
    
	
		
};
var bindEvent={
    saveteam:function(){
        $("#save").on("click",function(){
            var team_name=$("#new_team").val();         
            $.post("http://localhost:8080/contacts/group/add",{
                data:team_name
            })
        })
    },
    save_people:function(){
        
        $("#save_people").on("click",function(){
        var people_data={};
        var entriesArr=[];
        var entriesList = $(".choose_select input:checked");
            for(var i = 0; i < entriesList.length; i++){
        var entryData = {
            gid:$(entriesList[i]).attr("id"),
        };
        entriesArr.push(entryData);
        }
        people_data.cid=GetQueryString("id");
        people_data.name=$("#name").val();
        people_data.email=$("#email").val();
        people_data.tel=$("#tel").val();
        people_data.address=$("#address").val();
        people_data.birthday=$("#born").val();
        people_data.workPlace=$("#work_place").val();
        people_data.postCode=$("#codes").val();
        people_data.others=$("#remarks").val();
        people_data.qq=$("#QQ").val();
        people_data.homePage=$("#personal_page").val();
        people_data.phone=$("#phone").val();
        people_data.group = entriesArr;
       
        console.log(people_data);
       $.ajax({
        url: "http://localhost:8080/contacts/contact/update",
        type: 'post',
        dataType: 'JSON',
        data:{"data": JSON.stringify(people_data)},
        
        success:function(data){
                   var text = data.result;
                  if(text==0){
                    alert("success");
                  }else{
                   alert("error");
                  }
                }
       

    });

        

 })
       
    }

};
var render={
    initList:function(){
        var cid=GetQueryString("id");
        $.getJSON("http://localhost:8080/contacts/contact/query",{
            data:cid
        },function(contact){
            $.each(contact,function(idx,item){
                $("#choose_people").attr("src","http://localhost:8080/contacts/"+item.photo);
                $("#name").val(item.name);
                $("#email").val(item.email);
                $("#telphone").val(item.tel);
                $("#born").val(item.birthday);
                $("#address").val(item.address);
                $("#QQ").val(item.qq);
                $("#personal_page").val(item.homepage);
                $("#work_place").val(item.workPlace);
                $("#codes").val(item.postCode);
                $("#remarks").val(item.others);
                $("#tel").val(item.tel);
                $("#phone").val(item.phone);
                $("#personal_page").val(item.homePage);
            var checkbox=$(".choose_select input:checkbox");
            for(i=0;i<checkbox.length;i++){
                for(j=0;j<item.group.length;j++){
                if(checkbox[i].value==item.group[j]){
                    $(checkbox[i]).attr("checked",true);
                }
            }
            }
                
            })
        })
    }
}
var add={
    addteam:function(){
        $("#add").on("click",function(){
            $("#mymodal").modal("toggle");
        })
    },
    newteam:function(){
             $("#team_list").append('<li><a href="group_list.html">'+"所有分组"+'</li>');
        $.getJSON("http://localhost:8080/contacts/group/queryAll",function(groups){
                    $.each(groups.groups,function(idx,item){
                    $("#team_list").append('<li><a href="group_people.html?id='+item.gid+'">'+item.groupName+'</li>');
                     $(".choose_select").append('<label><input type="checkbox" id="'+item.gid+'" value="'+item.groupName+'"><span>'+item.groupName+'</span></label>');                       
                    })
                   
        });
         
        $("#save").on("click",function(){
            $("#team_list").append('<li>'+$("#new_team").val()+'</li>');
           
        });
        
    },
   
};
    

Date.prototype.format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
var time={
	choose_born:function(){
		var curDate = new Date();
	$('#born').datepicker({format: 'yyyy-mm-dd',
			language: 'zh-CN',
			 autoclose: true});
	$('#born')[0].value=curDate.format('yyyy-MM-dd');
	var d1 = $('#born').val();
	
	}
};
var button={
	back:function(){
		$("#back").on("click",function(){
				window.location.href="index.html"
		})		
	},
	mail_list:function(){
		$("#mail_list").on("click",function(){
			window.location.href="index.html"
		})
	}
};
var form={
	checkform:function(){
		$("#commentForm").validate({		
                 rules:{
                 	name:"required",
                 	email:{
                 		required:true,
                 		email:true
                 	},
                 	telphone:{
                 		required:true,
                 		digits:true                 			
                 	},
                 	address:{
                 		required:true
                 	},
                 	QQ:{
                 		required:true,
                 		digits:true
                 	},
                 	personal_page:{
                 		required:true,
                 		url:true
                 	},
                 	work_place:{
                 		required:true
                 	},
                 	remarks:{
                 		required:true,
                 		
                 	},
                 	codes:{
                 		required:true,
                 		digits:true
                 	},
                 	// team:{
                 	// 	required:true,
                 		
                 	// }

                 },
                 // messages:{
                 // 	team:{
                 // 		required:"请至少选择一个"
                 // 	}
                 // }
		});
	}
	

}